import React, { useState, useEffect, useCallback, useRef } from 'react'
import _EB from '../../eventbus'

// chat message 原封不动返回
function ChatMessage(data, from) {
    const message = {
        from: from || '匿名',
        type: 'chat-message',
        data
    }
    return JSON.stringify(message)
}
function ModifyUinfoMessage(data) {
    const message = {
        from: data.name,
        type: 'modify-uinfo',
        data
    }
    return JSON.stringify(message)
}

function useRefState(initValue) {
    const [value, setValue] = useState(initValue)
    const ref = useRef(initValue)
    function setV(value) {
        setValue(value)
        ref.current = value
    }
    return [value, ref, setV]
}

export default function ({
    con
}) {
    const [list, listRef, setList] = useRefState([])
    const [name, setName] = useState('')
    const [text, setText] = useState('')

    useEffect(() => {
        _EB.on('_CHAT_MSG', data => setList([...listRef.current, data]))
        _EB.on('_CHANGE_UINFO_SUCC', data => {
            alert('修改成功')
            setName(data.data.data)
        })
    }, [])

    function send() {
        if (!con.current) {
            return alert('请先链接')
        }
        // 发送消息
        con.current.send(ChatMessage({
            type: 'text',
            data: text
        }, name))
        // 清空text
        setText('')
    }

    function wsChangeName(value) {
        if (!con.current) {
            return alert('请先链接')
        }
        // 发送消息
        con.current.send(ModifyUinfoMessage({
            name: value
        }))
    }

    function keypress(e) {
        if (e.charCode === 13) {
            send()
        }
    }

    return <div className='chat-box'>
        {/* 聊天内容 */}
        <ChatList list={list} name={name} />
        <NameInput value={name} onChange={wsChangeName} />
        {/* 输入框 */}
        <div className='chat-input'>
            <input type="text" value={text} onChange={e => setText(e.target.value)} onKeyPressCapture={keypress} />
            <button onClick={send}>发送</button>
        </div>
    </div>
}

function ChatList({ list, name }) {
    return <div className='chat-list'>
        {
            list.map(item => <div className='row'>
                <div className={item.from === name ? 'right' : 'left'}>
                    <div>{item.from}:</div>
                    <div className='chat-item'>{item.data.data}</div>
                </div>
            </div>)
        }
    </div>
}

function NameInput({
    value,
    onChange
}) {
    const [edit, setEdit] = useState(false)
    const [text, setText] = useState('')
    useEffect(() => {
        console.log(value)
        setText(value)
        setEdit(false)
    }, [value])
    return <div className='name-input'>
        <span>昵称：</span>
        {
            edit
                ? <div>
                    <input value={text} onChange={e => setText(e.target.value)} type="text" />
                    <button onClick={() => onChange(text)}>确定</button>
                    <button onClick={() => {
                        setText(value)
                        setEdit(false)
                    }}>取消</button>
                </div>
                : <span onDoubleClick={() => setEdit(true)}>{text || '匿名'}</span>
        }
    </div>
}